<template>
  <el-dialog
    v-model="dialogVisible"
    :destroy-on-close="true"
    :align-center="true"
    width="50%"
    :title="`${dialogData.title}开票信息`"
  >
    <div class="info-wrapper" v-if="dialogData.isView">
      <el-alert title="当前开票已完成，不可以修改" type="error" show-icon :closable="false" effect="dark" />
    </div>
    <el-form
      ref="jobFormRef"
      :rules="rules"
      :disabled="dialogData.isView"
      :model="dialogData.itemInfo"
      label-width="180px"
      label-suffix=" :"
    >
      <div class="info-title">基本信息</div>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="开票编号">
            <el-input size="large" placeholder="开票编号" v-model="dialogData.itemInfo.billingNo" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开票金额">
            <el-input size="large" placeholder="开票金额" v-model="dialogData.itemInfo.billingAmt" disabled />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="联系人" prop="contactor">
            <el-input
              placeholder="请填写联系人"
              v-model="dialogData.itemInfo.contactor"
              size="large"
              maxlength="15"
              show-word-limit
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="contactorPhone">
            <el-input
              placeholder="请填写联系人电话"
              v-model="dialogData.itemInfo.contactorPhone"
              size="large"
              maxlength="15"
              show-word-limit
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="开票说明">
        <el-input
          v-model="dialogData.itemInfo.note"
          placeholder="请输入开票说明"
          type="textarea"
          rows="4"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
      <div class="info-title">开票明细</div>
      <div class="btn-wrapper">
        <el-form-item>
          <el-button type="primary" :icon="Plus" @click="handleAddWorkTime">添加开票明细</el-button>
        </el-form-item>
      </div>
      <el-form-item>
        <div class="work-wrapper">
          <div class="item-wrapper" v-for="(item, index) in dialogData.charges" :key="index">
            <div class="item-s" v-if="item.flagErr">
              <el-icon color="red"><CloseBold /></el-icon>
            </div>
            <div class="item-s">
              <span># {{ index + 1 }}</span>
            </div>
            <div class="item">
              <el-select v-model="item.id" placeholder="请选择充值明细" style="width: 100%" @change="handleChangeitem">
                <el-option v-for="item in dialogData.canCharges" :key="item.id" :label="item.payCnt" :value="item.id">
                  <span style="float: left">{{ item.payCnt }}</span>
                  <span style="float: right; color: var(--el-text-color-secondary); font-size: 13px">
                    [{{ item.chargeUserName }}]{{ item.createDate }}
                  </span>
                </el-option>
              </el-select>
            </div>
            <div class="item">
              <el-input v-model="item.createDate" disabled placeholder="充值时间" />
            </div>
            <div class="item">
              <el-button type="danger" :icon="Delete" size="small" circle @click="handleRemoveWorkTime(index)" />
            </div>
          </div>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">关闭</el-button>
      <el-button type="primary" size="large" v-show="!dialogData.isView" @click="handleSubmit" :loading="btnLoading">
        保存
      </el-button>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { getOptTitle, OptEnum, sysEnum } from "@/biz/eenum/appEnum";
import { DialogParam } from "@/biz/interface/DialogType";
import { ElMessage, FormInstance } from "element-plus";
import { reactive, ref } from "vue";
import {
  saveCompanyBillingApi,
  getCompanyBillingInfoApi,
  getCompanyCanBillingChargesListApi,
  getCompanyBillingChargesListApi
} from "@/api/modules/cpy/coin";
import { Delete, Plus, CloseBold } from "@element-plus/icons-vue";
import { CompanyBillingEntity, CompanyBillingChargeEntity } from "@/biz/interface/CompanyType";

interface PostDialogOption extends DialogParam {
  //弹出表单的标题
  title: string;
  // 是否是查看状态，查看状态是不可以提交数据
  isView: boolean;
  //当前的数据对象
  itemInfo: CompanyBillingEntity;
  // 已选择的充值
  charges: CompanyBillingChargeEntity[];
  // 当前所有的可开票的数据
  canCharges: CompanyBillingChargeEntity[];
}

//提交按钮，避免多次提交
const btnLoading = ref(false);
//弹出框的参数
const dialogVisible = ref(false);
const dialogData = reactive<PostDialogOption>({
  optType: OptEnum.CREATE,
  title: "",
  isView: false,
  itemInfo: {
    // * 联系人
    contactor: "",
    // * 联系电话
    contactorPhone: ""
  },
  charges: [],
  canCharges: []
});

//数据较验
const rules = reactive({
  contactor: [{ required: true, message: "请填写联系人", trigger: "blur" }],
  contactorPhone: [{ required: true, message: "请填写联系电话", trigger: "blur" }]
});

//页面事件
const emits = defineEmits(["refresh-list"]);

// 提交数据（新增/编辑）
const jobFormRef = ref<FormInstance>();
const handleSubmit = () => {
  btnLoading.value = true;
  jobFormRef.value!.validate(async valid => {
    if (!valid) {
      btnLoading.value = false;
      return;
    }
    try {
      if (dialogData.optType === OptEnum.CREATE || dialogData.optType === OptEnum.EDIT) {
        if (!dialogData.charges || dialogData.charges.length == 0) {
          ElMessage.error("开票明细不能为空");
          return;
        }

        let flagErr = false;

        let chargeIds: string[] = [];
        dialogData.charges.forEach(item => {
          if (item && item.id) {
            chargeIds.push(item.id);
            if (item.flagErr) {
              flagErr = true;
            }
          }
        });

        if (flagErr) {
          ElMessage.error("开票明细中有错误标识的为重复数据,请处理一下");
          return;
        }

        if (!chargeIds || chargeIds.length == 0) {
          ElMessage.error("开票明细不能为空");
          return;
        }

        let res = await saveCompanyBillingApi({
          ...dialogData.itemInfo,
          chargeIds
        });
        if (res.data) {
          ElMessage.success({ message: `保存成功！` });
          //刷新列表数据
          // eslint-disable-next-line vue/custom-event-name-casing
          emits("refresh-list");
          dialogVisible.value = false;
        }
      }
    } catch (error) {
      // console.log("出现异常情况,", error);
    } finally {
      btnLoading.value = false;
    }
  });
};

// 添加一个时间段
const handleAddWorkTime = () => {
  if (dialogData.charges && dialogData.charges.length > 4) {
    ElMessage.error("开票明细最多可以 5 条");
    return;
  }

  dialogData.charges.push({});
};

//移除一个时间段
const handleRemoveWorkTime = (idx: number) => {
  dialogData.charges.splice(idx, 1);
};

// 接收父组件传过来的参数
const acceptParams = (params: DialogParam): void => {
  dialogData.optType = params.optType;
  dialogData.rowData = params.rowData;

  dialogData.title = getOptTitle(dialogData.optType);

  loadCanBilling();

  // 初始可操作
  dialogData.isView = false;

  if (dialogData.optType === OptEnum.CREATE) {
    initItemInfo();
  } else if (dialogData.rowData && dialogData.rowData.id) {
    getItemInfo(dialogData.rowData.id);
  }

  dialogVisible.value = true;
};

//初始化页面的数据
const initItemInfo = (): void => {
  dialogData.itemInfo = {
    contactor: "",
    contactorPhone: "",
    note: ""
  };
  dialogData.charges = [{}];
};

//获取当前数据的详情，直接调用接口获取数据
const getItemInfo = async (id: string) => {
  if (id) {
    let { data } = await getCompanyBillingInfoApi({ id });
    dialogData.itemInfo = data as unknown as CompanyBillingEntity;

    // 通过明细去查数据
    if (dialogData.itemInfo && dialogData.itemInfo.chargeIds) {
      //dialogData.charges = dialogData.itemInfo.chargeIds;

      dialogData.isView = dialogData.itemInfo.status == sysEnum.EIGHT;

      let res = await getCompanyBillingChargesListApi({
        ids: dialogData.itemInfo.chargeIds
      });

      console.log(res.data);
      dialogData.charges = [];
      if (res && res.data) {
        res.data.forEach(element => {
          dialogData.canCharges.push({
            id: element.id,
            payCnt: element.payCnt,
            createDate: element.createDate
          });
          dialogData.charges.push({
            id: element.id,
            createDate: element.createDate
          });
        });
      }
    }
  }
};

const handleChangeitem = item => {
  console.log(item, dialogData.charges);
  if (item) {
    // 从源数组中的找出相同的id的对角，把数据填充进来
    let curObj = dialogData.canCharges.find(obj => {
      return obj.id == item;
    });
    if (dialogData.charges && curObj) {
      dialogData.charges.forEach(citem => {
        citem.flagErr = false;
        if (citem.id == item) {
          citem.createDate = curObj?.createDate;
          // citem.chargeUserName = curObj.chargeUserName;
        }
      });
    }
    checkSameItem(item);
  }
};

const checkSameItem = item => {
  let sameCnt = 0;
  // item 为当前的选择id. 在dialogData.charges中去过滤，查找当前项, 如果有二项以上。表示重复了。把重复的显示出来
  if (dialogData.charges) {
    dialogData.charges.forEach(citem => {
      if (citem.id == item) {
        sameCnt++;
      }
    });
  }
  if (sameCnt > 1) {
    dialogData.charges.forEach(citem => {
      if (citem.id == item) {
        citem.flagErr = true;
        sameCnt++;
      }
    });
  }
};

const loadCanBilling = async () => {
  // console.log("开始去取数据");
  let { data } = await getCompanyCanBillingChargesListApi({});
  // console.log("接收到的可开票的充值 ", data);
  if (data) {
    dialogData.canCharges = data.list as unknown as CompanyBillingChargeEntity[];
  }
};

//页面参数
defineExpose({
  acceptParams
});
</script>
<style scoped lang="scss">
.file-upload-box {
  display: flex;
  width: 100%;
  // border: 1px solid red;
}

.work-wrapper {
  display: flex;
  flex-direction: column;
  width: 100%;

  .btn-wrapper {
    height: 30px;
    // border: 1px solid red;
  }
  .item-wrapper {
    margin: 5px 0;
    // border: 1px solid green;

    display: flex;
    align-items: center;
    justify-content: center;

    .item-s {
      width: 5%;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .item {
      width: 30%;
      margin: 2px 5px;
    }
  }
}
.info-wrapper {
  width: 100%;
  border: 1px solid red;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
